package com.leapp.sk.view.im

import android.content.Context
import android.support.v4.view.ViewPager
import android.util.AttributeSet
import android.view.View
import android.widget.AdapterView
import android.widget.GridView
import com.leapp.sk.R
import com.leapp.sk.bean.EmojiconEntity
import com.leapp.sk.bean.EmojiconGroupEntity
import java.util.ArrayList
import com.leapp.sk.bean.EmojiconEntity.Type
import com.leapp.sk.ui.adapter.EmojiconGridAdapter
import com.leapp.sk.ui.adapter.EmojiconPagerAdapter
import com.leapp.sk.util.im.EmojiconUtils

/**
 * 表情ViewPager
 * @author  chaohaipeng  on 2018/7/13.
 */
class SKEmojiconPagerView : ViewPager {
    /**
     * 上下文
     */
    var mContext: Context? = null
//    /**
//     * 表情集合
//     */
//    var grouplist= listOf<EmojiconGroupEntity>()
    /**
     * 表情集合
     */
    var groupEntities= mutableListOf<EmojiconGroupEntity>()


    /**
     * 表情行数
     */
    private val emojiconRows = 3
    /**
     * 表情列数
     */
    private var emojiconColumns = 7
    /**
     * 动态表情行数
     */
    private val bigEmojiconRows = 2
    /**
     * 动态表情行数
     */
    private var bigEmojiconColumns = 4
    /**
     * 视图集合
     */
    private var viewpages: MutableList<View>? = null

    /**
     * 表情pager适配器
     */
    private var pagerAdapter: EmojiconPagerAdapter? = null


    private var firstGroupPageSize: Int = 0

    private var maxPageCount: Int = 0
    private var previousPagerPosition: Int = 0
    private var pagerViewListener: EaseEmojiconPagerViewListener? = null
    constructor(context: Context) : super(context) {
        mContext = context
    }


    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        mContext = context
    }

    fun init(emojiconGroupList: List<EmojiconGroupEntity>?, emijiconColumns: Int, bigEmojiconColumns: Int) {
        if (emojiconGroupList == null) {
            throw RuntimeException("emojiconGroupList is null")
        }
        this.emojiconColumns = emijiconColumns
        this.bigEmojiconColumns = bigEmojiconColumns
        viewpages = ArrayList()
        groupEntities.addAll(emojiconGroupList)
        if (groupEntities!=null){
            for (i in groupEntities.indices) {
                val group = groupEntities.get(i)
                val gridViews = getGroupGridViews(group)
                if (i == 0) {
                    firstGroupPageSize = gridViews.size
                }
                maxPageCount = Math.max(gridViews.size, maxPageCount)
                viewpages?.addAll(gridViews)
            }

            pagerAdapter = EmojiconPagerAdapter(viewpages)
            adapter = pagerAdapter
            addOnPageChangeListener(EmojiPagerChangeListener())
            pagerViewListener?.onPagerViewInited(maxPageCount, firstGroupPageSize)
        }

    }

    /**
     * get emojicon group gridview list
     * @param groupEntity
     * @return
     */
    fun getGroupGridViews(groupEntity: EmojiconGroupEntity): List<View> {
        val emojiconList = groupEntity.emojiconList
        var itemSize = emojiconColumns * emojiconRows - 1
        val totalSize = emojiconList?.size
        val emojiType = groupEntity.type
        if (emojiType === EmojiconEntity.Type.BIG_EXPRESSION) {
            itemSize = bigEmojiconColumns * bigEmojiconRows
        }
        if(totalSize!=null&&itemSize!=null){
            val pageSize = if (totalSize % itemSize == 0) totalSize / itemSize else totalSize / itemSize + 1
            val views = ArrayList<View>()
            for (i in 0..(pageSize-1)) {
                val view = View.inflate(context, R.layout.sk_emojicon_gridview, null)
                val gv = view.findViewById<GridView>(R.id.gv_seg) as GridView
                if (emojiType === Type.BIG_EXPRESSION) {
                    gv.numColumns = bigEmojiconColumns
                } else {
                    gv.numColumns = emojiconColumns
                }
                val list = ArrayList<EmojiconEntity>()
                if (i != pageSize - 1) {
                    list.addAll(emojiconList.subList(i * itemSize, (i + 1) * itemSize))
                } else {
                    list.addAll(emojiconList.subList(i * itemSize, totalSize))
                }
                if (emojiType !== Type.BIG_EXPRESSION) {
                    val deleteIcon = EmojiconEntity()
                    deleteIcon.emojiText= EmojiconUtils.DELETE_KEY
                    list.add(deleteIcon)
                }
                val gridAdapter = EmojiconGridAdapter(context,  list, emojiType)
                gv.adapter = gridAdapter
                gv.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id ->
                    val emojicon:EmojiconEntity = list.get(position)
                    if (pagerViewListener != null) {
                        val emojiText = emojicon.emojiText
                        if (emojiText != null && emojiText == EmojiconUtils.DELETE_KEY) {
                            pagerViewListener?.onDeleteImageClicked()
                        } else {
                            pagerViewListener?.onExpressionClicked(emojicon)
                        }

                    }
                }
                views.add(view)
        }
            return views
        }else{
            return emptyList()
        }
    }


    /**
     * add emojicon group
     * @param groupEntity
     */
    fun addEmojiconGroup(groupEntity: EmojiconGroupEntity, notifyDataChange: Boolean) {
        val pageSize = getPageSize(groupEntity)
        if (pageSize > maxPageCount) {
            maxPageCount = pageSize
            if (pagerViewListener != null && pagerAdapter != null) {
                pagerViewListener?.onGroupMaxPageSizeChanged(maxPageCount)
            }
        }
        viewpages?.addAll(getGroupGridViews(groupEntity))
        groupEntities.add(groupEntity)
        if (pagerAdapter != null && notifyDataChange) {
            pagerAdapter?.notifyDataSetChanged()
        }
        pagerViewListener?.onPagerViewInited(maxPageCount, firstGroupPageSize)
    }

    /**
     * remove emojicon group
     * @param position
     */
    fun removeEmojiconGroup(position: Int) {
        if (groupEntities!=null){
            if (position > groupEntities.size - 1) {
                return
            }
            if (pagerAdapter != null) {
                pagerAdapter?.notifyDataSetChanged()
            }
        }

    }

    /**
     * get size of pages
     * @param emojiconList
     * @return
     */
    private fun getPageSize(groupEntity: EmojiconGroupEntity): Int {
        val emojiconList = groupEntity.emojiconList
        var itemSize = emojiconColumns * emojiconRows - 1
        if(emojiconList!=null){
            val totalSize = emojiconList.size
            val emojiType = groupEntity.type
            if (emojiType === Type.BIG_EXPRESSION) {
                itemSize = bigEmojiconColumns * bigEmojiconRows
            }
            return if (totalSize % itemSize == 0) totalSize / itemSize else totalSize / itemSize + 1
        }
         return 1
    }

    private inner class EmojiPagerChangeListener : ViewPager.OnPageChangeListener {
        override fun onPageSelected(position: Int) {
            var endSize = 0
            var groupPosition = 0
            if (groupEntities!=null){
                for (i in groupEntities.indices) {
                    val groupPageSize = getPageSize(groupEntities.get(i))
                    //if the position is in current group
                    if (endSize + groupPageSize > position) {
                        //this is means user swipe to here from previous page
                        if (previousPagerPosition - endSize < 0) {
                            pagerViewListener?.onGroupPositionChanged(groupPosition, groupPageSize)
                            pagerViewListener?.onGroupPagePostionChangedTo(0)
                            break
                        }
                        //this is means user swipe to here from back page
                        if (previousPagerPosition - endSize >= groupPageSize) {
                            pagerViewListener?.onGroupPositionChanged(groupPosition, groupPageSize)
                            pagerViewListener?.onGroupPagePostionChangedTo(position - endSize)
                            break
                        }

                        //page changed
                        if (pagerViewListener != null) {
                            pagerViewListener?.onGroupInnerPagePostionChanged(previousPagerPosition - endSize, position - endSize)
                        }
                        break

                    }
                    groupPosition++
                    endSize += groupPageSize
                }

                previousPagerPosition = position
            }

        }

        override fun onPageScrollStateChanged(arg0: Int) {}
        override fun onPageScrolled(arg0: Int, arg1: Float, arg2: Int) {}
    }

    fun setPagerViewListener(pagerViewListener: EaseEmojiconPagerViewListener) {
        this.pagerViewListener = pagerViewListener
    }

    /**
     * set emojicon group position
     * @param position
     */
    fun setGroupPostion(position: Int) {
            if ( position >= 0 && position < groupEntities?.size) {
                var count = 0
                for (i in 0..(position-1)) {
                    count += getPageSize(groupEntities?.get(i))
                }
                currentItem = count
            }
    }
    interface EaseEmojiconPagerViewListener {
        /**
         * pagerview initialized
         * @param groupMaxPageSize --max pages size
         * @param firstGroupPageSize-- size of first group pages
         */
        fun onPagerViewInited(groupMaxPageSize: Int, firstGroupPageSize: Int)

        /**
         * group position changed
         * @param groupPosition--group position
         * @param pagerSizeOfGroup--page size of group
         */
        fun onGroupPositionChanged(groupPosition: Int, pagerSizeOfGroup: Int)

        /**
         * page position changed
         * @param oldPosition
         * @param newPosition
         */
        fun onGroupInnerPagePostionChanged(oldPosition: Int, newPosition: Int)

        /**
         * group page position changed
         * @param position
         */
        fun onGroupPagePostionChangedTo(position: Int)

        /**
         * max page size changed
         * @param maxCount
         */
        fun onGroupMaxPageSizeChanged(maxCount: Int)

        fun onDeleteImageClicked()
        fun onExpressionClicked(emojicon: EmojiconEntity)

    }


}